import { app } from "../../../scripts/app.js";

app.registerExtension({
  name: "kraken.tools",
  async beforeRegisterNodeDef(nodeType, nodeData, app) {

    const attachPreview = () => {
      const onNodeCreated = nodeType.prototype.onNodeCreated;
      nodeType.prototype.onNodeCreated = function () {
        const r = onNodeCreated ? onNodeCreated.apply(this, []) : undefined;
        const imgElement = document.createElement("img");
        imgElement.style = "width: 100%; height: auto; display: block; margin: 5px 0;";
        this.previewWidget = this.addDOMWidget("preview", "custom", imgElement, { serialize: false });
        return r;
      };

      const onExecuted = nodeType.prototype.onExecuted;
      nodeType.prototype.onExecuted = function (message) {
        if (onExecuted) onExecuted.apply(this, [message]);
        if (message && message.images && message.images.length > 0 && this.previewWidget) {
          const img = this.previewWidget.value;
          const { filename, subfolder, type } = message.images[0];
          const url = `/view?filename=${encodeURIComponent(filename)}&type=${encodeURIComponent(type || "temp")}&subfolder=${encodeURIComponent(subfolder || "")}&rand=${Math.random()}`;
          img.src = url;
        }
      };
    };

    if (nodeData.name === "KrakenFluxEmptyLatentImage") attachPreview();
    if (nodeData.name === "KrakenUpscaleTileCalc") attachPreview();
  },
});
